package com.dy.basic.controller;

import com.dy.basic.service.VerifyCodeService;
import com.dy.basic.util.AjaxResult;
import com.dy.basic.util.BusinessException;
import com.dy.user.dto.EmailRegisterFormDto;
import com.dy.user.dto.PhoneRegisterFormDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private VerifyCodeService verifyCodeService;

    @GetMapping("/image/{imageCodeKey}")
    public AjaxResult graph(@PathVariable("imageCodeKey") String imageCodeKey){
        try {
            String base64 = verifyCodeService.graph(imageCodeKey);
            return AjaxResult.me().setResultObj(base64);
        }catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙!!!");

        }
    }

    @PostMapping("/smsCode")
    public AjaxResult smsCode(@RequestBody  @Valid PhoneRegisterFormDto phoneRegisterFormDto){
        try {
            verifyCodeService.smsCode(phoneRegisterFormDto);
            return AjaxResult.me().setSuccess(true);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙");

        }
    }

    /**
     * 邮箱注册获取验证码
     */
    @GetMapping("/sendEmailCode/{email}")
    public AjaxResult sendEmailCode(@PathVariable("email") String email){
        try {
            String emailUUID = verifyCodeService.sendEmailCode(email);
            return AjaxResult.me().setSuccess(true).setResultObj(emailUUID);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙");

        }
    }

}
